<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" >新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="warning" @click="onsale" >上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale" >下架</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <!--
      :data="products" - 绑定的数据[]
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框/忙等框
      @selection-change="selsChange" - 选项改变
      批量删除：type="selection - 选项
    -->
		<el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
      <el-table-column prop="name" label="名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="resources" label="资源" width="160" sortable>
        <template scope="scope">
          <img :src="imgPrefix+scope.row.resources" height="50px">
        </template>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80">
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">上架</span>
          <span style="color: red" v-else-if="scope.row.state==0">下架</span>
          <span style="color: darkslategray" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价格" width="160" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="160" sortable>
      </el-table-column>
      <el-table-column prop="salecount" label="出售数量" width="160" sortable>
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)" >编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" >删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'product:patch'">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :current-page="currentPage" :total="totals" style="float:right;">
      </el-pagination>
		</el-col>

    <!--添加和修改的对话框-->
    <!--
      :close-on-click-modal="false" - 点击对话外面的区域不关闭对话框
      :model="saveForm" - 绑定表单数据
      :rules="saveFormRules" - 校验规则
      ref="saveForm" - 对话框的名称 - 验证的时候需要用
      auto-complete="off" - 自动完成
    -->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item prop="resources" label="图片">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastdfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

	export default {
    components: {
      quillEditor
    },
		data() {
			return {
        quillOption: quillConfig,
			  //分页相关数据
        fileList: [],
        products: [],
        totals:0,
        pageSize:5,
        currentPage:1,
        listLoading: false,


        //高级查询所需数据
        keyword: '',//关键字查询


        //模型数据data,多条数据选中,用于删除
				sels: [],//列表选中列

				saveFormVisible: false, //对话框是否显示：默认不显示
				saveLoading: false,     //对话框中的加载框/忙等框
        title:'',               //标题
				saveFormRules: {        //校验规则
					sn: [
            //在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入部门的编号
						{ required: true, message: '请输入部门编号', trigger: 'blur' }
					],
          name: [
            //在失去焦点的时候，校验name是否为空，如果为空，就会显示红色的请输入部门的名称
            { required: true, message: '请输入部门名称', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				saveForm: {
          id:null,
          name:null,
          resources:null,
          // saleprice:'',
          // offsaletime:null,
          // onsaletime:null,
          state:0,
          // costprice:'',
          // createtime:null,
          // salecount:null,
          productDetail:{  //与后端实体类一致
            productId:null,
            intro: '',
            orderNotice: ''
          }

				},
        //列表显示图片的前缀
        imgPrefix: "http://123.207.27.208",
			}
		},
		methods: {

      //上传一张图片的时候会触发
      handleSuccess(response, file, fileList){
        //1.处理resources
        if(this.saveForm.resources){
          this.saveForm.resources = this.saveForm.resources+","+response.resultObj;
        }else {
          this.saveForm.resources=response.resultObj;
        }
        this.fangfa();
      },


      handleRemove:function (file, fileList){
        //1.调用删除接口删除 fastdfs上的图片
        let url = file.url;
        let path = url.substring(url.indexOf("/group"));
        this.$http.delete("/fastdfs?path=" + path).then(res=>{
          if (res.data.success){
            this.$message.success("删除成功");
          }else {
            this.$message.error("删除失败");
          }
        })

        //2.对resource做处理 ：加入path="/group1/MxVcQ8663.jpg"
        if (this.saveForm.resources){
          let arr = this.saveForm.resources.split(",")
          for (var i = 0;i<arr.length;i++){
            if (arr[i] == path){
              //从i开始删除，向后删除1个
              arr.splice(i,1);
              break;
            }
          }
          this.saveForm.resources = arr.join(","); // /group1/M00cQ8663.jpg,/group1/MxVcQ8663.jpg
        }
        //3.对fileList做处理
        this.fangfa();
      },
      fangfa(){
        this.fileList=[];
        if (this.saveForm.resources){
          let arr = this.saveForm.resources.split(",");
          for(var i = 0;i<arr.length;i++){
            this.fileList.push({"url":"http://123.207.27.208" + arr[i]});
          }
        }
      },

      //上架业务
      onsale(){
        var ids = this.sels.map(item => item.id);
        //获取选中的行
        if(!this.sels || this.sels.length  <1){
          this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
          return;
        }
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$http.patch("/product/onsale",ids).then(res=>{
            if (res.data.success){ //上架成功
              this.$message.success("上架成功") //3s自动消失
              this.getProducts();
            }else {
              this.$message.error(res.data.message);
            }
          }).catch(res=>{
            this.$message.error('系统繁忙，请稍后重试【400,404】');
          })
        }).catch(() => {
        });
      },

      //下架业务
      offsale(){
        var ids = this.sels.map(item => item.id);
        //获取选中的行
        if(!this.sels || this.sels.length  <1){
          this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
          return;
        }
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$http.patch("/product/offsale",ids).then(res=>{
            if (res.data.success){ //下架成功
              this.$message.success("下架成功") //3s自动消失
              this.getProducts();
            }else {
              this.$message.error('系统繁忙，请稍后重试【500】');
            }
          }).catch(res=>{
            this.$message.error('系统繁忙，请稍后重试【400,404】');
          })
        }).catch(() => {
        });
      },

      //1.分页查询：获取部门列表
      getProducts() {
        let para = {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          keyword:this.keyword
        };
        this.listLoading = true;

        this.$http.post("/product",para).then((res) => {
          this.totals = res.data.totals;
          this.products = res.data.data;
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error('系统繁忙，请稍后重试!!!');
        });
      },


      //2.点击某一页触发的方法
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getProducts();
      },


      //3.关键字查询
      keywordQuery(){
        this.currentPage = 1;
        this.getProducts();
      },


      //4.删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '温馨提示', {
          type: 'warning'
        }).then(() => { //点击确认之后要执行的代码
          //显示加载框
          this.listLoading = true;
          //获取id
          var id= row.id;
          this.$http.delete("/product/"+id).then(res=>{
            if (res.data.success){ //删除成功
              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.pageSize == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }
              this.$message.success("删除成功") //3s自动消失
              this.getProducts();
            }else {
              this.$message.error('系统繁忙，请稍后重试【500】');
            }
            this.listLoading = false;//关闭加载框
          }).catch(res=>{
            this.$message.error('系统繁忙，请稍后重试【400,404】');
          })
        }).catch(() => { //点击取消之后要执行的代码
        });
      },


      //5.选项改变触发此方法
      selsChange: function (sels) {
        //获取被选中的对象  - 集合
        this.sels = sels;
      },


      //6.批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$http.patch("/product",ids).then(res=>{
            if (res.data.success){ //删除成功
              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.pageSize == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }
              this.$message.success("删除成功") //3s自动消失
              this.getProducts();
            }else {
              this.$message.error('系统繁忙，请稍后重试【500】');
            }
            this.listLoading = false;//关闭加载框
          }).catch(res=>{
            this.$message.error('系统繁忙，请稍后重试【400,404】');
          })
        }).catch(() => {
        });
      },


      //7.点击添加按钮弹出对话框,增加功能要重置
      handleAdd: function () {
        this.saveForm = {
          id: null,
          name:null,
          resources:null,
          // saleprice:'',
          // offsaletime:null,
          // onsaletime:null,
          state:0,
          // costprice:'',
          // createtime:null,
          // salecount:null,
          productDetail:{
            intro: '',
            orderNotice: ''
          }
        };
        this.title = " 添 加 "
        this.saveFormVisible = true;
        this.fangfa();
      },


      //8.点击修改按钮弹出对话框
      handleEdit: function (index, row) {
        //克隆：防止对象引用修改显示的数据
        this.saveForm = Object.assign({}, row);
        this.title = " 修 改 ";



        //显示对话框
        //this.getProducts();
        this.fangfa();
        this.saveFormVisible = true;
      },


      //9.点击提交按钮添加或修改数据
      saveSubmit: function () {
          this.$refs.saveForm.validate((valid) => {
            if (valid) {
              this.$confirm('确认提交吗？', '提示', {}).then(() => {
                this.saveLoading = true;
                let para = Object.assign({}, this.saveForm);


                this.$http.put("/product",para).then(res=>{
                  if (res.data.success){
                    this.$message.success("操作成功！")
                    this.getProducts()
                  }else {
                    this.$message.error("系统繁忙，请稍后重试。【500】")
                  }
                  this.saveLoading=false;//不显示加载框
                  this.saveFormVisible=false;//不显示对话框
                }).catch(res=>{
                  this.$message.error("系统繁忙，请稍后重试。【400】,【404】")
                })
              });
            }
          });
        },



		},
		mounted() {
			this.getProducts();
		}
	}

</script>

<style scoped>

</style>